import {App, MenuService, SettingsService, User} from '@delon/theme';
import {Component, OnDestroy, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {SocialService, SocialOpenType} from '@delon/auth';
import {environment} from '@env/environment';
import {AppUrl} from '../../../app.url';
import {HttpClient} from '@angular/common/http';
import {ACLService} from '@delon/acl';
import {APP_ROLE} from '../../../app.role';

@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less'],
    providers: [SocialService]
})
export class UserLoginComponent implements OnDestroy, OnInit {

    form: FormGroup;
    error = '';
    type = 0;
    roleType: any = ''; //
    loading = false;

    constructor(fb: FormBuilder,
                private router: Router,
                public msg: NzMessageService,
                private settingsService: SettingsService,
                private socialService: SocialService,
                private aclService: ACLService,
                private http: HttpClient,
                private menuSrv: MenuService,
                private _message: NzMessageService) {
        this.form = fb.group({
            userName: [null, [Validators.required]],
            password: [null, Validators.required],
            mobile: [null, [Validators.required]],
            captcha: [null, [Validators.required]],
            remember: [true]
        });
    }

    // region: fields

    get userName() {
        return this.form.controls.userName;
    }

    get password() {
        return this.form.controls.password;
    }

    get mobile() {
        return this.form.controls.mobile;
    }

    get captcha() {
        return this.form.controls.captcha;
    }

    // endregion

    switch(ret: any) {
        this.type = ret.index;
    }

    // region: get captcha

    count = 0;
    interval$: any;

    getCaptcha() {
        this.count = 59;
        this.interval$ = setInterval(() => {
            this.count -= 1;
            if (this.count <= 0)
                clearInterval(this.interval$);
        }, 1000);
        this.http.post(AppUrl.login.getLoginCaptchaUrl, {phoneNum: this.mobile.value})
            .subscribe(data => {
                let temp: any;
                temp = data;
                if (temp.code) {
                }
            });
    }

    // endregion

    loginSubmit(): void {

        this.error = '';
        if (this.type === 0) {
            this.userName.markAsDirty();
            this.password.markAsDirty();
            if (this.userName.invalid || this.password.invalid) return;
        } else {
            this.mobile.markAsDirty();
            this.captcha.markAsDirty();
            if (this.mobile.invalid || this.captcha.invalid) return;
        }
        // mock http
        this.loading = true;
        if (this.type === 0) {
            // act login
            this.http.post(AppUrl.login.loginUrl, {username: this.userName.value, password: this.password.value})
                .subscribe(data => {
                    console.log(data);
                    this.valueHandler(data);
                }, reject => {
                    this.errorHandler(reject);
                });
        } else {
            // mobile login
            this.http.post(AppUrl.login.loginUrl, {phoneNum: this.mobile.value, confirmCode: this.captcha.value})
                .subscribe(data => this.valueHandler(data), reject => {
                    this.errorHandler(reject);
                });
        }
    }

    /**
     * 登录认证统一处理
     */
    valueHandler(data) {
        this._message.success('登录成功,欢迎回来', {nzDuration: 3000});
        this.loading = false;
        let temp: any;
        temp = data;
        if (temp.code && temp.code === 200) {
            localStorage.setItem('token', 'Bearer ' + temp.data.token);
            localStorage.setItem('userid', temp.data.userInfo.userid);
            localStorage.setItem('username', this.userName.value);
            localStorage.setItem('roletype', temp.data.userInfo.roletype);
            let user:User = {
                name:temp.data.userInfo.username,
            };
            this.settingsService.setUser(user);
            let _that = this;
            this.aclService.setFull(false);
            this.roleType = temp.data.userInfo.roletype;
            if (this.roleType.includes('A') || this.roleType === 'B' || this.roleType === 'S') {
                this.aclService.setRole([this.roleType]);
                let ability = [];
                if (temp.data.ability && temp.data.ability.length > 0)
                    temp.data.ability.forEach(e => {
                        ability.push(e.ability_value)
                    });
                this.aclService.attachAbility(ability);
                console.log(this.aclService.data);
            }
            else {
                this.aclService.setRole(['T']);
                alert('非法的角色，进入游客模式');
            }
            this.menuSrv.resume();
            let appConf: App = {
                name: '辛易校园',
                description: '校园赞助平台',
                menuShow: true
            };
            _that.settingsService.setApp(appConf);
            this.router.navigate(['/']);
        } else if (temp.status) {
            document.getElementById('alert').style.display = 'block';
            setTimeout(() => {
                document.getElementById('alert').style.display = 'none';
            }, 3000);
        }

    }

    /**
     * 错误处理
     */

    errorHandler(reject) {
        this.aclService.setFull(false);
        //设置为游客模式
        this.aclService.setRole(['T']);
        this.menuSrv.resume();
        if (reject && reject.error && reject.error.status) {
            let status = reject.error.status;
            if (status === 401) {
                this._message.warning('登录失败,用户名或密码错误', {nzDuration: 3000});
            }
            else {
                this._message.error('服务器异常,请稍后重试', {nzDuration: 3000});
            }
        }
        else {
            this._message.error('服务器异常,请稍后重试', {nzDuration: 3000});
        }
        this.loading = false;
    }

    // endregion

    ngOnDestroy(): void {
        if (this.interval$) clearInterval(this.interval$);
    }

    ngOnInit(): void {
        localStorage.setItem('token', '');
    }

}
